package com.shallwead.bna.util.image;

import java.lang.ref.WeakReference;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;

public class ImageDownloader {
	public final int IMGAE_CACHE_LIMIT_SIZE = 100;
	// public static HashMap<String, Bitmap> mImageCache = new HashMap<String,
	// Bitmap>();
	public static LRUCache<String, Bitmap> mImageCache = new LRUCache<String, Bitmap>(
			30);

	Context context;
	ImageCache imageCache = null;

	public ImageDownloader(Context context) {
		this.context = context;
	}

	public void download(String url, ImageView imageView) {

		try {
			imageCache = ImageCacheFactory.getInstance().get(url);
		} catch (NullPointerException e) {
		}

		Bitmap cachedImage = null;
		try {
			cachedImage = imageCache.getBitmap(url);
		} catch (NullPointerException e) {
		}
		// Bitmap cachedImage = mImageCache.get(url);
		if (cachedImage != null) {
			imageView.setImageBitmap(cachedImage);
			imageView.setScaleType(ImageView.ScaleType.FIT_XY);

		} else if (cancelPotentialDownload(url, imageView)) {
			// if (mImageCache.size() > IMGAE_CACHE_LIMIT_SIZE) {
			// mImageCache.clear();
			// }
			imageView.setScaleType(ImageView.ScaleType.FIT_XY);

			ImageDownloaderTask task = new ImageDownloaderTask(url, imageView,
					imageCache);
			DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);

			imageView.setImageDrawable(downloadedDrawable);
			imageView.setScaleType(ImageView.ScaleType.FIT_XY);

			task.execute(url);
		}

	}

	private boolean cancelPotentialDownload(String url, ImageView imageView) {
		ImageDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);

		if (bitmapDownloaderTask != null) {
			String bitmapUrl = bitmapDownloaderTask.url;
			if ((bitmapUrl == null) || (!bitmapUrl.equals(url))) {
				bitmapDownloaderTask.cancel(true);
			} else {
				return false;
			}
		}
		return true;
	}

	private ImageDownloaderTask getBitmapDownloaderTask(ImageView imageView) {
		if (imageView != null) {
			Drawable drawable = imageView.getDrawable();
			if (drawable instanceof DownloadedDrawable) {
				DownloadedDrawable downloadedDrawable = (DownloadedDrawable) drawable;
				return downloadedDrawable.getBitmapDownloaderTask();
			}
		}
		return null;
	}

	class DownloadedDrawable extends ColorDrawable {
		private final WeakReference<ImageDownloaderTask> bitmapDownloaderTaskReference;

		public DownloadedDrawable(ImageDownloaderTask bitmapDownloaderTask) {
			super(Color.TRANSPARENT);
			bitmapDownloaderTaskReference = new WeakReference<ImageDownloaderTask>(
					bitmapDownloaderTask);
		}

		public ImageDownloaderTask getBitmapDownloaderTask() {
			return bitmapDownloaderTaskReference.get();
		}
	}
}
